# -*- encoding: utf-8 -*-
import network
import ujson
import time
from  aliyunIoT import Device
from esp32 import NVS
import esp


ICCID=None
global info
g_connect_status = False
net = None
device = None
deviceSecret = None
device_dyn_resigter_succed = False
nvs = None
# wifi热点信息



mqtt_connect_flag=False
#当iot设备连接到物联网平台的时候触发'connect' 事件
def on_connect(data):
    global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade,mqtt_connect_flag
    print('***** connect lp succeed :{}****'.format(data))
    data_handle = {}
    mqtt_connect_flag=True
    data_handle['device_handle'] = device.getDeviceHandle()

#当连接断开时，触发'disconnect'事件
def on_disconnect():
    print('linkkit is disconnected')

#当iot云端下发属性设置时，触发'props'事件
def on_props(request):
    print('clound req data is {}'.format(request))

#当iot云端调用设备service时，触发'service'事件
def on_service(id,request):
    print('clound req id  is {} , req is {}'.format(id,request))
#当设备跟iot平台通信过程中遇到错误时，触发'error'事件
def on_error(err):
    print('err msg is {} '.format(err))    

#动态注册回调函数
def on_dynreg_cb(data):
    print('aliyun dynreg success')
    global deviceSecret,device_dyn_resigter_succed
    deviceSecret = data
    print(f'devicesecret:{deviceSecret}')
    device_dyn_resigter_succed = True

 # 连接物联网平台
def dyn_register_device(productKey,productSecret,deviceName):
    global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed
    global nvs
    key = '_devicesecret'  #键值固定
    deviceSecretdict = bytearray(32)

    #获取设备密钥
    try:
        nvs.get_blob(key, deviceSecretdict)
    except OSError as e:
        print(f"Error: {e}")

    if(all(x == 0 for x in deviceSecretdict)) :
        key_info = {
            'productKey': productKey  ,
            'productSecret': productSecret ,
            'deviceName': deviceName
        }
        if not device_dyn_resigter_succed:
            device.register(key_info,on_dynreg_cb)  
    else:
        # 动态注册一个设备，获取设备的deviceSecret
        #下面的if防止多次注册，当前若是注册过一次了，重启设备再次注册就会卡住，
        deviceSecret = deviceSecretdict.decode('utf-8') 
        print("deviceSecret:",deviceSecret)

def connect_wifi(ssid,pwd):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep(2)
    wlan.connect(ssid, pwd)
    while not wlan.isconnected():
        pass
    print('network config: ', wlan.ifconfig())

def demo(deviceName,productKey,productSecret,ssid,pwd):
    global module_name,default_ver,on_trigger,on_download,device,nvs,mqtt_connect_flag
    esp.osdebug(5)
    # 连接网络
    connect_wifi(ssid,pwd)

    nvs = NVS('aos_kv')
    # # 删除键值对
    # status = nvs.erase_key("_devicesecret")
    # print(status,'================')

    #初始化物联网平台Device类，获取device实例
    device = Device()
    
    if deviceName is not None and len(deviceName) > 0 :
     #动态注册一个设备
        dyn_register_device(productKey,productSecret,deviceName)
    else:
        print("can not dynamic reg")
    while deviceSecret is None:
        time.sleep(0.2)
    print('dynamic reg success:' + deviceSecret)
    
    key_info = {
        'region' : 'cn-shanghai' ,
        'productKey': productKey ,
        'deviceName': deviceName ,
        'deviceSecret': deviceSecret ,
        'keepaliveSec': 60,
        }
    #打印设备信息
    print(key_info)

    device.on(device.ON_CONNECT,on_connect)
    device.on(device.ON_DISCONNECT,on_disconnect)
    device.on(device.ON_PROPS,on_props)
    device.on(device.ON_SERVICE,on_service)
    device.on(device.ON_ERROR,on_error)
    device.connect(key_info)
    time.sleep(1)
    while not mqtt_connect_flag:
        time.sleep_ms(200)
    #上报版本信息
    FwVersion={}
    FwVersion["FwVersion"]="ed1_haas_v1.0"
    FwVersionStr=ujson.dumps(FwVersion)
    data0={
        'params':FwVersionStr
    }
    time.sleep_ms(1000)
    device.postProps(data0)
    


if __name__ == '__main__':
    demo()